#!/usr/bin/env python3
# -*- coding: utf-8 -*-

 # 函数式编程-》高阶函数 begin
# def add(x, y, f):
#     return f(x) + f(y)

# r = add(-1, 5, abs)
# def f(x):
#     return x**2
# r = map(f, range(1, 4))
# print(r)
# r1 = map(str, range(1,4))
# print(r1)
# from functools import reduce
# # reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4) 求和
# def add(x, y):
#     return x + y
# def fn(x, y):
#     return x*10+y    
# r = reduce(add, range(1, 4)) # sum
# r1 = sum(range(1, 4))
# r2 = reduce(fn, range(1, 4))
# print(r)
# print(r1)
# print(r2)
# from functools import reduce

# DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

# def char2num(s):
#     digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
#     return digits[s]

# def str2int2(s):
#     return reduce(lambda x, y: x * 2 + y, map(char2num, s))    

# def str2int(s):
#     def fn(x, y):
#         return x * 2 + y
#     def char2num(s):
#         return DIGITS[s]
#     return reduce(fn, map(char2num, s))
# r = str2int('123') # reduce(fn, [1, 2, 3]) -> 1*2 + 2 , (1*2 + 2)*2 + 3 = 11
# r1 = char2num('2')
# r2 = str2int2('123')
# print(r)
# print(r1)
# print(r2)

# # ex
# def normalize(name):
#     if not isinstance(name, str):
#         print 'Error'
#         return 'Error'
#     return name[0].upper() + name[1:].lower()

# L1 = ['adam', 'LISA', 'barT']
# L2 = list(map(normalize, L1))
# print(L2)

# def prod(L):
#     def fn(x, y):
#         return x * y
#     return reduce(fn, L)

# def prod2(L):
#     return reduce(lambda x, y: x * y, L)

# print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
# if prod([3, 5, 7, 9]) == 945:
#     print('测试成功!')
# else:
#     print('测试失败!')
# print(prod2([3, 5, 7, 9]))
# if prod2([3, 5, 7, 9]) == 945:
#     print('测试成功2!')
# else:
#     print('测试失败2!')
# def is_odd(n):
#     return n % 2 == 1

# def not_empty(s):
#     return s and s.strip()    

# def _odd_iter():
#     n = 1
#     while True:
#         n = n + 2
#         yield n

# def _not_divisible(n):
#     return lambda  x: x % n > 0

# def primes():
#     yield 2
#     it = _odd_iter()
#     print('it:', it)
#     while True:
#         n = next(it)
#         yield n
#         print('n:', n)
#         it = filter(_not_divisible(n), it)
#         yield it

# for n in primes():
#     if n < 1000:
#         print('for:', n)
#     else:
#         break

# print(filter(is_odd, [1, 2, 4, 5, 6]))
# print(filter(not_empty, ['A', '', 'B', None, 'C', '  ']))

### sorted begin
# print(sorted([36, 5, -1, 9, -22]))
# print(sorted([36, 5, -1, 9, -22], key=abs))
# print(sorted(['bob', 'about', 'Zoo', 'Credit']))
# print(sorted(['bob', 'about', 'Zoo', 'Credit'], reverse=True))
# print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower))
# s = '1234'
# print(s[::-1])
# print(sorted(s, reverse=True))

# L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]

# def by_name(t):
#     return t[0]

# def by_score(t):
#     return t[1]

# L2 = sorted(L, key=by_name)
# L3 = sorted(L, key=by_score)
# L4 = sorted(L, key=lambda t: t[1])
# print(L2)
# print(L3)
# print(L4)
### sorted end

### 返回函数

# def count():
#     fs = []
#     for i in range(1, 4):
#         def f():
#             print('in i:', i)
#             return i * i
#         print('out i:', i)    
#         fs.append(f)    
#     print('fs:',fs)    
#     print(fs[0](), fs[1](), fs[2]())
#     return fs    

# f1, f2, f3 = count()
# print(f1 == f2)
# print(f1(), f2(), f3())

# ('out i:', 1)
# ('out i:', 2)
# ('out i:', 3)
# ('fs:', [<function f at 0x10dda6050>, <function f at 0x10dda6668>, <function f at 0x10dda6d70>])
# ('in i:', 3)
# ('in i:', 3)
# ('in i:', 3)
# (9, 9, 9)
# False
# ('in i:', 3)
# ('in i:', 3)
# ('in i:', 3)
# (9, 9, 9)

# print(len(f1))
# def calc_sum(*args):
#     ax = 0
#     for n in args:
#         ax = ax + n
#     return ax
# def lazy_sum(*args):
#     def sum():
#         ax = 0
#         for n in args:
#             ax = ax + n
#         return ax
#     return sum   

# def createCounter():
#     def plus():
#         n = 0        
#         while True:
#             n = n + 1            
#             yield n
#     x = plus()
#     def counter():
#         return next(x)
#     return counter  # return 的 函数地址

# # def createCounter():
# #     n = 0
# #     def counter():
# #         nonlocal n
# #         n = n + 1
# #         return n
# #     return counter

# ca = createCounter() # ca 就等于一个函数地址
# cb = createCounter() # cb 和 ca 是2个地址
# print(ca(), ca())

## 匿名函数
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5])))

def is_odd(n):
    return n % 2 == 1
L = list(filter(is_odd, range(1, 20)))
L1 = list(filter(lambda n: n % 2 == 1, range(1, 20)))
print(L)    
print(L1)    
## 匿名函数

## 装饰器
# @log
# def now():
#     print('2019-11-21')
# f = now  
# f()
# print(f.__name__)
# print(now.__name__)
## 装饰器

### 返回函数

# 函数式编程-》高阶函数 end

# 迭代器 begin
# from collections import Iterable
# print(isinstance([], Iterable))
# print(isinstance({}, Iterable))
# print(isinstance('abc', Iterable))
# print(isinstance((x for x in range(10)), Iterable))
# print(isinstance(100, Iterable))
# 迭代器 end

# 生成器 generator begin
# L = [x * x for x in range(10)] # list
# print(L)
# g = (x * x for x in range(10)) # generator
# print(g)
# for n in g:
# 	print(n)
#print(next(g))
#print(next(g))
#print(next(g))

# 斐波拉契数列
# def fib(max):
# 	n, a, b = 0, 0, 1
# 	while n < max:
# 		yield b#print(b)
# 		a, b = b, a + b
# 		n = n + 1
# 	#return 'done'

# for n in fib(6):
# 	print(n)

# # 杨辉三角
# def triangles():
# 	L = [1]
# 	while True:
# 		yield L 
# 		L1 = [L[0]]
# 		for n in range(1, len(L)):
# 			L1.append(L[n-1]+L[n])
# 		L1.append(1)
# 		L = L1

# # 期待输出:
# # [1]
# # [1, 1]
# # [1, 2, 1]
# # [1, 3, 3, 1]
# # [1, 4, 6, 4, 1]
# # [1, 5, 10, 10, 5, 1]
# # [1, 6, 15, 20, 15, 6, 1]
# # [1, 7, 21, 35, 35, 21, 7, 1]
# # [1, 8, 28, 56, 70, 56, 28, 8, 1]
# # [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
# n = 0
# results = []
# for t in triangles():
#     results.append(t)
#     n = n + 1
#     if n == 10:
#         break

# for t in results:
#     print(t)

# if results == [
#     [1],
#     [1, 1],
#     [1, 2, 1],
#     [1, 3, 3, 1],
#     [1, 4, 6, 4, 1],
#     [1, 5, 10, 10, 5, 1],
#     [1, 6, 15, 20, 15, 6, 1],
#     [1, 7, 21, 35, 35, 21, 7, 1],
#     [1, 8, 28, 56, 70, 56, 28, 8, 1],
#     [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
# ]:
#     print('测试通过!')
# else:
#     print('测试失败!')

# def odd():
# 	print('step 1')
# 	yield 1	# 遇见yield就返回
# 	print('step 2')
# 	yield(3)
# 	print('step 3')
# 	yield(5)
 
# o = odd()
# next(o)
# next(o)
# next(o)
# next(o) # 无yield 就越界了

# 生成器 generator end

# 迭代
# from collections import Iterable
# r = isinstance('abc', Iterable)
# t = isinstance((1, 2, 3), Iterable)
# y = isinstance(123, Iterable)
# print(r)
# print(t)
# print(y)

# for i, value in enumerate(['a', 'b', 'c']):
# 	print(i, value)

# for x, y in [(1, 2), (2, 4), (3, 9), (5, 25)]:
# 	print(x, y)

# def findMinAndMax(L):
# 	if len(L) == 0:
# 		return (None, None)
# 	if len(L) == 1:
# 		return (L[0], L[0])

# 	l, r = (L[0], L[0])

# 	for v in L:
# 		if l >= v:
# 			l = v
# 		if r <= v:
# 			r = v	
# 	print('l=', l, ', r=', r)			
# 	return (l, r)

# # 测试
# if findMinAndMax([]) != (None, None):
#     print('测试失败 0!')
# elif findMinAndMax([7]) != (7, 7):
#     print('测试失败 1!')
# elif findMinAndMax([7, 1]) != (1, 7):
#     print('测试失败 2!')
# elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
#     print('测试失败 3!')
# else:
#     print('测试成功 4!')

# L = []
# for x in range(1, 11):
# 	L.append(x * x)

# print(L)

# L1 = [x * x for x in range(1, 11)]
# print(L1)

# L2 = [x * x for x in range(1, 11) if x % 2 == 0]
# print(L2, ', ', len(L2))

# L3 = [m + n for m in 'ABC' for n in 'XYZ']# m + n 表示字符串结合
# print(L3)

# import os # 导入os模块
# L4 = [d for d in os.listdir('.')]
# print(L4)

# d = {'x': 'A', 'y': 'B', 'z': 'C'}
# for k, v in d.items():
# 	print(k, '=', v)

# L5 = [k + '=' + v for k, v in d.items()]	
# print(L5)

# L6 = ['HELLO', 'World', 'IBM', 'Apple']
# L7 = [s.lower() for s in L6]
# print(L7)

# L8 = ['Hello', 'world', 18, 'Apple', None]
# L9 = [s.lower() for s in L8 if isinstance(s, str)]
# print(L9)
# if L9 == ['hello', 'world', 'apple']:
#     print('测试通过!')
# else:
#     print('测试失败!')

# import math

# def fact(n):
# 	if n == 1:
# 		return 1
# 	return n * fact(n - 1)
	
# r = fact(4)		
# print(r)

# *args是可变参数，args接收的是一个tuple；
# **kw是关键字参数，kw接收的是一个dict。
# def f1(a, b, c=0, *args, **kw):
# 	print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)

# def f2(a, b, c=0, *, d, **kw):
# 	print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)

# f1(1, 2)
# f1(1, 2, 3, 'a', 'b')
# f1(1, 2, 3, 'a', 'b', x=99)
# f2(1, 2, d=99, ext=None)

# def person(name, age, **kw):
# 	if 'city' in kw:
# 		print('city ok')
# 	if 'job' in kw:
# 		print('job ok')
# 	print('name:', name, 'age:', age, 'other:', kw)

# person('jack', 24, city='beijing', addr='chaoyang')	

# def calc(*numbers): # 可变参数， ** 表示可以0个或任意个
# 	sum = 0
# 	for n in numbers:
# 		sum = sum + n * n
# 	return sum

# print(calc(1, 2, 3))	

# def enroll(name, gender):
# 	print('name', name)
# 	print('gender', gender)

# print('aaaa')
# enroll('ccc', 'ddd')	

# def power(x, n=2):
# 	return x ** n
# print(power(2))
# def auadratic(a, b, c):
# 	x = math.sqrt(b * b- 4*a*c)
# 	y = math.sqrt(b * b - 4*a*c)
# 	x = x / 2*a
# 	y = y / 2*a
# 	return x, y
# r = auadratic(1, 4, 1)
# print(r)	

# def move(x, y, step, angle=0):
# 	nx = x + step * math.cos(angle)
# 	ny = y - step * math.sin(angle)
# 	return nx, ny

# x, y = move(100, 100, 60, math.pi/6)
# r = move(100, 100, 60, math.pi/6)
# print(x, y)
# print(r)

# def nop():
# 	pass

# def my_abs(x):
# 	if not isinstance(x, (int, float)):
# 		raise TypeError('bad operand type')
# 	if x >= 0:
# 		return x
# 	else:
# 		return -x

# print(my_abs('-99'))			

# n = 1
# while n <= 100:
# 	n += 1
# 	if n == 5:
# 		continue
# 	print(n)
# 	if n > 10:
# 		break
# print('END')	

# names = ['a', 'b', 'c']
# for name in names:
# 	print(name)

# sum = 0
# for x in range(101):
# 	sum += x
# print(sum)

# height = 1.62
# weight = 63.5

# bmi = weight / height**2

# if bmi < 18.5:
# 	print('过轻')
# elif bmi < 25:
# 	print('正常')
# elif bmi < 28:
# 	print('过重')	
# elif bmi < 32:
# 	print('肥胖')
# else:
# 	print('严重肥胖')


# # print('birth: ')
# birth = input()
# s = int(birth)
# if s < 2000:
# 	print('00前')
# else:
# 	print('00后')	

# if <条件判断1>:
#     <执行1>
# elif <条件判断2>:
#     <执行2>
# elif <条件判断3>:
#     <执行3>
# else:
#     <执行4>

# if x: # x 为非零，非空字串，非空list等，判定为True，否则为Fasle
#     print('True')

# age = 3

# if age >= 18:
# 	print('adult')
# elif age >= 6:
#     print('teenager')
# else:
# 	print('kid')

# print('your age is', age)
# if age >= 18:
#     print('adult')
# else:
#     print('teenager')    

# L = [
#     ['Apple', 'Google', 'Microsoft'],
#     ['Java', 'Python', 'Ruby', 'PHP'],
#     ['Adam', 'Bart', 'Lisa']
# ]
# for x in range(0,len(L)):
# 	print(L[x])
# print(L[0][0])
# print(L[1][1])
# print(L[2][2])

# s1 = 72
# s2 = 85
# r = (s2 - s1) / s1 * 100
# print('r: %02.1f %%' % r)
# print('r: {0:02.1f} %'.format(r))

# print('please input name:')
# name = input()
# print('hello, world', name)

# a = 'ABC'
# b = a
# a = 'XYZ'
# print(b)